#import "ItemRecordViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ItemRecordViewController ()
@end

@implementation ItemRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记住这东西";
    
    // 设置渐变背景
    CAGradientLayer *backgroundGradient = [CAGradientLayer layer];
    backgroundGradient.colors = @[(__bridge id)[UIColor colorWithRed:1.0 green:0.98 blue:0.94 alpha:1.0].CGColor,
                                  (__bridge id)[UIColor colorWithRed:0.98 green:0.96 blue:0.92 alpha:1.0].CGColor];
    backgroundGradient.frame = self.view.bounds;
    [self.view.layer insertSublayer:backgroundGradient atIndex:0];
    
    // 优化导航栏
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0];
    self.navigationController.navigationBar.titleTextAttributes = @{
        NSForegroundColorAttributeName: [UIColor blackColor],
        NSFontAttributeName: [UIFont systemFontOfSize:20 weight:UIFontWeightMedium]
    };
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    UIImage *backImage = [UIImage imageNamed:@"back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [self loadItemRecords];
    if (!self.itemRecords) {
        self.itemRecords = [NSMutableArray arrayWithArray:@[
            @{@"name":@"老花镜", @"desc":@"放在客厅茶几上", @"category":@"日用品", @"time":@"2小时前"},
            @{@"name":@"钥匙", @"desc":@"放在玄关鞋柜上的小盒子里", @"category":@"重要物品", @"time":@"昨天"}
        ]];
    }
    self.selectedCategory = @"全部";
    
    // 优化分类按钮设计
    NSArray *categories = @[@"全部", @"日用品", @"药品", @"重要物品"];
    CGFloat btnW = (self.view.bounds.size.width - 60) / categories.count;
    
    UIView *categoryContainer = [[UIView alloc] initWithFrame:CGRectMake(20, 100, self.view.bounds.size.width - 40, 50)];
    categoryContainer.backgroundColor = [UIColor whiteColor];
    categoryContainer.layer.cornerRadius = 25;
    categoryContainer.layer.shadowColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:0.1].CGColor;
    categoryContainer.layer.shadowOpacity = 1;
    categoryContainer.layer.shadowOffset = CGSizeMake(0, 4);
    categoryContainer.layer.shadowRadius = 10;
    [self.view addSubview:categoryContainer];
    
    for (int i = 0; i < categories.count; i++) {
        UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        catBtn.frame = CGRectMake(10 + btnW * i, 10, btnW - 10, 30);
        [catBtn setTitle:categories[i] forState:UIControlStateNormal];
        
        BOOL isSelected = [categories[i] isEqualToString:self.selectedCategory];
        if (isSelected) {
            // 选中状态：橙色背景，白色文字
            catBtn.backgroundColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0];
            [catBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            catBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
            // 添加选中状态的阴影
            catBtn.layer.shadowColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:0.3].CGColor;
            catBtn.layer.shadowOpacity = 1;
            catBtn.layer.shadowOffset = CGSizeMake(0, 2);
            catBtn.layer.shadowRadius = 4;
        } else {
            // 未选中状态：透明背景，橙色文字
            catBtn.backgroundColor = [UIColor clearColor];
            [catBtn setTitleColor:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0] forState:UIControlStateNormal];
            catBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
            // 清除阴影
            catBtn.layer.shadowOpacity = 0;
        }
        
        catBtn.layer.cornerRadius = 15;
        catBtn.tag = 200 + i;
        [catBtn addTarget:self action:@selector(filterCategory:) forControlEvents:UIControlEventTouchUpInside];
        [categoryContainer addSubview:catBtn];
    }
    
    // 表格
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 170, self.view.bounds.size.width, self.view.bounds.size.height - 270) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    // 优化底部按钮设计
    UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(20, self.view.bounds.size.height - 90, self.view.bounds.size.width - 40, 60)];
    buttonContainer.backgroundColor = [UIColor whiteColor];
    buttonContainer.layer.cornerRadius = 30;
    buttonContainer.layer.shadowColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:0.15].CGColor;
    buttonContainer.layer.shadowOpacity = 1;
    buttonContainer.layer.shadowOffset = CGSizeMake(0, 6);
    buttonContainer.layer.shadowRadius = 15;
    [self.view addSubview:buttonContainer];
    
    // 拍照记录按钮
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    photoBtn.frame = CGRectMake(15, 10, (buttonContainer.bounds.size.width - 45) / 2, 40);
    
    CAGradientLayer *photoGradient = [CAGradientLayer layer];
    photoGradient.colors = @[(__bridge id)[UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0].CGColor,
                             (__bridge id)[UIColor colorWithRed:0.85 green:0.45 blue:0.20 alpha:1.0].CGColor];
    photoGradient.frame = photoBtn.bounds;
    photoGradient.cornerRadius = 20;
    [photoBtn.layer insertSublayer:photoGradient atIndex:0];
    
    photoBtn.layer.cornerRadius = 20;
    [photoBtn setTitle:@"📷 拍照记录" forState:UIControlStateNormal];
    [photoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    photoBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    [photoBtn addTarget:self action:@selector(addPhotoItem) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:photoBtn];
    
    // 语音记录按钮
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    voiceBtn.frame = CGRectMake(30 + (buttonContainer.bounds.size.width - 45) / 2, 10, (buttonContainer.bounds.size.width - 45) / 2, 40);
    voiceBtn.backgroundColor = [UIColor colorWithRed:0.96 green:0.98 blue:1.0 alpha:1.0];
    voiceBtn.layer.cornerRadius = 20;
    voiceBtn.layer.borderWidth = 2;
    voiceBtn.layer.borderColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0].CGColor;
    [voiceBtn setTitle:@"🎤 语音记录" forState:UIControlStateNormal];
    [voiceBtn setTitleColor:[UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0] forState:UIControlStateNormal];
    voiceBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    [voiceBtn addTarget:self action:@selector(addVoiceItem) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:voiceBtn];
}
- (void)cancelAction {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.selectedCategory isEqualToString:@"全部"]) return self.itemRecords.count;
    NSUInteger count = 0;
    for (NSDictionary *item in self.itemRecords) {
        if ([item[@"category"] isEqualToString:self.selectedCategory]) count++;
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (NSDictionary *)itemForIndex:(NSInteger)row {
    if ([self.selectedCategory isEqualToString:@"全部"]) return self.itemRecords[row];
    NSMutableArray *filtered = [NSMutableArray array];
    for (NSDictionary *item in self.itemRecords) {
        if ([item[@"category"] isEqualToString:self.selectedCategory]) [filtered addObject:item];
    }
    return filtered[row];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"ItemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
        cell.backgroundColor = [UIColor clearColor];
        UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(16, 8, self.view.bounds.size.width-32, 84)];
        bg.backgroundColor = [UIColor whiteColor];
        bg.layer.cornerRadius = 16;
        bg.tag = 3001;
        // 卡片阴影
        bg.layer.shadowColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:0.12].CGColor;
        bg.layer.shadowOpacity = 1;
        bg.layer.shadowOffset = CGSizeMake(0, 4);
        bg.layer.shadowRadius = 8;
        [cell.contentView addSubview:bg];
        // 物品图片缩略图
        UIImageView *thumb = [[UIImageView alloc] initWithFrame:CGRectMake(24, 22, 40, 40)];
        thumb.layer.cornerRadius = 12;
        thumb.layer.masksToBounds = YES;
        thumb.contentMode = UIViewContentModeScaleAspectFill;
        thumb.tag = 3005;
        [cell.contentView addSubview:thumb];
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(72, 18, self.view.bounds.size.width-200, 22)];
        name.font = [UIFont boldSystemFontOfSize:17];
        name.textColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0];
        name.tag = 3002;
        [cell.contentView addSubview:name];
        UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(72, 44, self.view.bounds.size.width-200, 18)];
        desc.font = [UIFont systemFontOfSize:15];
        desc.textColor = [UIColor grayColor];
        desc.tag = 3003;
        [cell.contentView addSubview:desc];
        // 修复时间标签宽度 - 增加宽度并调整位置
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-140, 18, 120, 20)];
        time.font = [UIFont systemFontOfSize:13];
        time.textColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
        time.textAlignment = NSTextAlignmentRight;
        time.tag = 3004;
        [cell.contentView addSubview:time];
    }
    NSDictionary *item = [self itemForIndex:indexPath.row];
    UILabel *name = [cell.contentView viewWithTag:3002];
    UILabel *desc = [cell.contentView viewWithTag:3003];
    UILabel *time = [cell.contentView viewWithTag:3004];
    UIImageView *thumb = [cell.contentView viewWithTag:3005];
    name.text = item[@"name"];
    desc.text = item[@"desc"];
    time.text = item[@"time"];
    if (item[@"imagePath"]) {
        thumb.image = [UIImage imageWithContentsOfFile:item[@"imagePath"]];
        thumb.hidden = NO;
    } else {
        thumb.image = nil;
        thumb.hidden = YES;
    }
    return cell;
}

// 选中物品，弹出详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [self itemForIndex:indexPath.row];
    NSString *msg = [NSString stringWithFormat:@"%@\n%@\n分类：%@\n记录时间：%@", item[@"name"], item[@"desc"], item[@"category"], item[@"time"]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"物品详情" message:msg preferredStyle:UIAlertControllerStyleAlert];
    if (item[@"imagePath"]) {
        [alert addAction:[UIAlertAction actionWithTitle:@"查看图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self showImageAtPath:item[@"imagePath"]];
        }]];
    }
    if (item[@"audioPath"]) {
        [alert addAction:[UIAlertAction actionWithTitle:@"播放录音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self playAudioAtPath:item[@"audioPath"]];
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"更新位置" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 修复：正确找到要删除的项目在原始数组中的索引
        NSInteger originalIndex = [self.itemRecords indexOfObject:item];
        if (originalIndex != NSNotFound) {
            [self.itemRecords removeObjectAtIndex:originalIndex];
            [self saveItemRecords];
            [self.tableView reloadData];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 展示大图
- (void)showImageAtPath:(NSString *)path {
    UIImage *img = [UIImage imageWithContentsOfFile:path];
    if (!img) return;
    UIViewController *imgVC = [[UIViewController alloc] init];
    imgVC.view.backgroundColor = [UIColor blackColor];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:imgVC.view.bounds];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.image = img;
    imgView.userInteractionEnabled = YES;
    [imgVC.view addSubview:imgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissImageVC:)];
    [imgView addGestureRecognizer:tap];
    [self presentViewController:imgVC animated:YES completion:nil];
}
- (void)dismissImageVC:(UITapGestureRecognizer *)tap {
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 播放录音
- (void)playAudioAtPath:(NSString *)path {
    static AVAudioPlayer *player = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
    [player play];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"正在播放" message:@"点击停止播放" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"停止" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [player stop];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 拍照记录
- (void)addPhotoItem {
    PhotoRecordViewController *photoVC = [[PhotoRecordViewController alloc] init];
    photoVC.delegate = self;
    [self.navigationController pushViewController:photoVC animated:YES];
}

// 语音记录
- (void)addVoiceItem {
    VoiceRecordViewController *voiceVC = [[VoiceRecordViewController alloc] init];
    voiceVC.delegate = self;
    [self.navigationController pushViewController:voiceVC animated:YES];
}

#pragma mark - PhotoRecordDelegate

- (void)didFinishPhotoRecordWithData:(NSDictionary *)itemData {
    [self.itemRecords addObject:itemData];
    [self saveItemRecords];
    [self.tableView reloadData];
}

#pragma mark - VoiceRecordDelegate

- (void)didFinishVoiceRecordWithData:(NSDictionary *)itemData {
    [self.itemRecords addObject:itemData];
    [self saveItemRecords];
    [self.tableView reloadData];
}

// 分类筛选 - 修复按钮样式更新
- (void)filterCategory:(UIButton *)sender {
    NSString *cat = sender.titleLabel.text;
    self.selectedCategory = cat;
    
    // 更新所有按钮的样式
    NSArray *categories = @[@"全部", @"日用品", @"药品", @"重要物品"];
    for (int i = 0; i < categories.count; i++) {
        UIButton *btn = [self.view viewWithTag:200 + i];
        BOOL isSelected = [cat isEqualToString:categories[i]];
        
        if (isSelected) {
            // 选中状态：橙色背景，白色文字
            btn.backgroundColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
            // 添加选中状态的阴影
            btn.layer.shadowColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:0.3].CGColor;
            btn.layer.shadowOpacity = 1;
            btn.layer.shadowOffset = CGSizeMake(0, 2);
            btn.layer.shadowRadius = 4;
        } else {
            // 未选中状态：透明背景，灰色文字
            btn.backgroundColor = [UIColor clearColor];
            [btn setTitleColor:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
            // 清除阴影
            btn.layer.shadowOpacity = 0;
        }
    }
    
    [self.tableView reloadData];
}

- (void)saveItemRecords {
    [[NSUserDefaults standardUserDefaults] setObject:self.itemRecords forKey:@"itemRecords"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)loadItemRecords {
    NSArray *saved = [[NSUserDefaults standardUserDefaults] objectForKey:@"itemRecords"];
    if (saved) {
        self.itemRecords = [saved mutableCopy];
    }
}

@end
